package com.daxidi.cn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxidi.cn.entity.*;
import com.daxidi.cn.mapper.LogMapper;
import com.daxidi.cn.mapper.MemberMapper;
import com.daxidi.cn.mapper.ShopMapper;
import com.daxidi.cn.mapper.UserMapper;
import com.daxidi.cn.params.LoginParam;
import com.daxidi.cn.service.IClerkService;
import com.daxidi.cn.service.IMemberService;
import com.daxidi.cn.service.IPwdManagerService;
import com.daxidi.cn.service.IUserService;
import com.daxidi.cn.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

@Log4j
@Api(tags = "登录接口")
@RestController
@RequestMapping("/api/v1/union/login")
public class LoginController {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IMemberService memberServicel;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IClerkService clerkService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private IPwdManagerService pwdManagerService;

    @ApiOperation(value = "会员  登录接口")
    @ApiResponses({
            @ApiResponse(code = 175, message = "登录成功"),
            @ApiResponse(code = 176, message = "用户名或密码错误"),
            @ApiResponse(code = 177, message = "尚未注册"),
            @ApiResponse(code = 916, message = "用户已下线，请联系管理员！"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @PostMapping("/")
    public ReturnResult loginMember(@RequestBody LoginParam loginParam) {
        if (loginParam.getType().equalsIgnoreCase("member")) {
            Long timestamp1 = System.currentTimeMillis();
            Member member = memberServicel.loginMember(loginParam.getMobile(), loginParam.getPassword());
            QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("mobile", loginParam.getMobile());
            Member member1 = memberMapper.selectOne(memberQueryWrapper);
            //查出管理员电话
            String mobile = pwdManagerService.queryPwdManager();
            if (ObjectUtils.isEmpty(member) && !ObjectUtils.isEmpty(member1)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("msg", "密码错误，请联系管理员" + mobile);
                return ReturnResultUtils.returnFailMsgAndData(176, "用户名或密码错误", map);
            }
            if (ObjectUtils.isEmpty(member) && ObjectUtils.isEmpty(member1)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("msg", "尚未注册，平台是泗洪工会，注册需要联系管理员" + mobile);
                return ReturnResultUtils.returnFailMsgAndData(177, "尚未注册", map);
            }
            if (member.getEnable() == 0) {
                HashMap<String, Object> hashMap = new HashMap();
                hashMap.put("msg", "用户已下线，请联系管理员！");
                hashMap.put("openId", loginParam.getOpenId());
                return ReturnResultUtils.returnFailMsgData(916, hashMap);
            }
            System.out.println("member = " + member);
            if (member != null) {
                try {
                    QueryWrapper<User> wrapper = new QueryWrapper<>();
                    wrapper.eq("membe_id", member.getId());
                    User user = userMapper.selectOne(wrapper);
                    user.setNickname(loginParam.getNickName());
                    user.setOpenId(loginParam.getOpenId());
                    user.setMobile(loginParam.getMobile());
                    user.setAvatarurl(loginParam.getAvatarUrl());
                    userService.updateUserByMemberId(user, user.getId());

                    HashMap<String, Object> map = new HashMap<>();
                    map.put("member", member);
                    String tokenName = null;
                    if (StringUtils.isEmpty(member.getName())) {
                        tokenName = loginParam.getNickName();
                    } else {
                        tokenName = member.getName();
                    }
                    String token = JWTUtils.generate(tokenName);
                    //redisUtils.set(ShgCons.TOKEN_MEMBER + token, JSON.toJSONString(member), 18000);
                    map.put("token", token);
                    //添加日志
                    Log log = new Log();
                    log.setLogAt(new Date(timestamp1));
                    String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
                    log.setLogIp(ipAddrByRequest);
                    log.setLogContent("会员登录");
                    log.setLogTime(System.currentTimeMillis() - timestamp1);
                    log.setLogType("SELECT");
                    log.setUsername(StringUtils.isEmpty(member.getName()) ? "未添加的用户名" : member.getName());
                    logMapper.insert(log);
                    return ReturnResultUtils.returnSuccess(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReturnResultUtils.returnFailMsg(177, "登录失败！");
                }
            } else {
                return ReturnResultUtils.returnFailMsg(176, "用户名或密码错误");
            }
        } else {
            Clerk clerk = clerkService.login(loginParam.getMobile(), loginParam.getPassword());
            if (ObjectUtils.isEmpty(clerk)) {
                return ReturnResultUtils.returnFailMsg(176, "用户名或密码错误");
            }
            if (clerk.getEnable() == false) {
                return ReturnResultUtils.returnFailMsg(845, "该店员已注销，请联系管理员！");
            }
            Long timestamp1 = System.currentTimeMillis();
            if (clerk != null) {
                QueryWrapper<User> wrapper = new QueryWrapper<>();
                wrapper.eq("clerk_id", clerk.getId());
                User user = userMapper.selectOne(wrapper);
                user.setNickname(loginParam.getNickName());
                user.setOpenId(loginParam.getOpenId());
                user.setMobile(loginParam.getMobile());
                user.setAvatarurl(loginParam.getAvatarUrl());
                userService.updateUserByClerkId(user, user.getId());

                HashMap<String, Object> map = new HashMap<>();
                map.put("clerk", clerk);
                redisUtils.set("manager", clerk.getName());
                String tokenName = null;
                if (StringUtils.isEmpty(clerk.getName())) {
                    tokenName = loginParam.getNickName();
                } else {
                    tokenName = clerk.getName();
                }
                String token = JWTUtils.generate(tokenName);
                //redisUtils.set(ShgCons.TOKEN_CLERK + token, JSON.toJSONString(clerk), 18000);
                map.put("token", token);
                QueryWrapper<Shop> shopQueryWrapper = new QueryWrapper<>();
                shopQueryWrapper.eq("id", clerk.getShopId());
                Shop shop = shopMapper.selectOne(shopQueryWrapper);
                map.put("discount", shop.getDiscount());
                //添加日志
                Log log = new Log();
                log.setLogAt(new Date(timestamp1));
                String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
                log.setLogIp(ipAddrByRequest);
                log.setLogContent("店员登录");
                log.setLogTime(System.currentTimeMillis() - timestamp1);
                log.setLogType("SELECT");
                log.setUsername(StringUtils.isEmpty(clerk.getName()) ? "未添加的用户名" : clerk.getName());
                logMapper.insert(log);
                return ReturnResultUtils.returnSuccess(map);
            } else {
                return ReturnResultUtils.returnFailMsg(176, "用户名或密码错误");
            }
        }
    }
}
